#include "app_uart1.h"

#include <string.h>

#include "main.h"
#include "usart.h"
#include "app_debug_printf.h"

uart1_rx_cb_t uart1_rx_cb = {.tail = 0};

uart1_rx_frame_queue_t uart1_rx_frame_queue = {.head = 0,
											   .tail = 0,
											   .remaining = UART1_RX_FRAME_NUM};

void uart1_rx_frame_enqueue(const uart1_rx_frame_t *frame)
{
	assert_param(frame != NULL);
	assert_param(uart1_rx_frame_queue.remaining != 0);

	memcpy(&(uart1_rx_frame_queue.buf[uart1_rx_frame_queue.tail++]), frame, sizeof(uart1_rx_frame_t));

	uart1_rx_frame_queue.tail %= UART1_RX_FRAME_NUM;
	uart1_rx_frame_queue.remaining--;
}

uint8_t uart1_rx_frame_dequeue(uart1_rx_frame_t *frame)
{
	assert_param(frame != NULL);

	if (uart1_rx_frame_queue.remaining == UART1_RX_FRAME_NUM)
	{
		return 0;
	}

	memcpy(frame, &(uart1_rx_frame_queue.buf[uart1_rx_frame_queue.head++]), sizeof(uart1_rx_frame_t));

	uart1_rx_frame_queue.head %= UART1_RX_FRAME_NUM;
	uart1_rx_frame_queue.remaining++;

	return 1;
}

void uart1_rx_start(void)
{
	HAL_UARTEx_ReceiveToIdle_DMA(&huart1, &uart1_rx_cb.buf[uart1_rx_cb.tail], UART1_RX_MAX_SIZE + 1);
}

void uart1_rx_test(void)
{
	uart1_rx_start();

	uart1_rx_frame_t frame;
	while (1)
	{
		if (uart1_rx_frame_dequeue(&frame))
		{
			debug_printf("has received %d datas from uart1:\r\n", frame.end - frame.start + 1);
			for (uint32_t i = 0; i < frame.end - frame.start + 1; ++i)
			{
				debug_printf("%c", uart1_rx_cb.buf[frame.start + i]);
			}
			debug_printf("\r\n");
		}
	}
}
